<?php
namespace app\thirdpart\controller;

use app\common\model as M;

/**
 *
 */
class Xiumi extends \think\Controller
{

	protected function _initialize()
    {
        parent::_initialize();

        try {
        	//if ( !$this->checkAuth() ) throw new \Exception("无权访问", 1);
        	
        } catch (\Exception $e) {
        	exception($e->getMessage()); 
        }
    }

    /**
     * 图片上传
     */
    public function image_upload()
    {
        try {
        	$file = request()->file('img-upload');
            $content_type = $file->getInfo()['type'];
            $path = explode('.' , $file->getInfo()['name']);
            $name = sha1_file($file->getInfo()['tmp_name']) . '.' . $path[1];

            $dir = 'files';
            if (preg_match('/video/' , $content_type)) $dir = 'videos';
            if (preg_match('/audio/' , $content_type)) $dir = 'audios';
            if (preg_match('/image/' , $content_type)) $dir = 'images';

            $res = \service\JSYService::upLoaderFile($file->getInfo()['tmp_name'] , $dir . '/' . $name , $content_type);
            if ( isset($res['ETag']) ) {
                return json_encode([
                    "code" => 0,
                    "msg"  => "",
                    "data" => [
                        "url"  => \service\JSYService::FILE_DOMAIN . $dir . '/' . $name,
                    ]
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                "code" => 101,
                "msg"  => $e->getMessage()
            ]);
        }

        return json_encode([
        	"code" => 101,
        	"msg"  => "图片上传失败"
        ]);
    }

    /**
     * 接收HTML
     */
    public function html_api()
    {
    	$post = json_decode(file_get_contents("php://input"),true);
    	$articles = $post['articles'] ?? [];
    	if ( !empty($articles) ) {
    		$res = M\RoutesDetails::syncArticles($articles);

    		if ( $res === true ) {
    			return json_encode([
	                "code" => 0,
	                "msg"  => "success",
	            ]);
    		}
    	}

    	return json_encode([
        	"code" => 101,
        	"msg"  => "HTML上传失败"
        ]);
    }

	public function notify_index()
	{
		$url = (new \service\XiumiEditorService)->generateBindUrl();
		echo $url;
	}

	protected function checkAuth()
	{
		$headerSecret = request()->header('Authorization');
		return (new \service\XiumiEditorService)->checkAuth($headerSecret);
	}
}